#include <QtGui/QApplication>
#include "qmlapplicationviewer.h"

//------------------------------------------------------
// ** instrumenting for Try & Buy functionality below **
#include "iapminimal.h"
#include <QSettings>
#include <QDir>

#define TNBSETTING "E0062A0B" // the value must match to the application UID
#define TNBCNTKEY "editor/wrapMargin"
const int TNBALLOWED = 3;

static void checkTNB(IAPminimal& iap);

// ** instrumenting for Try & Buy functionality above **
//------------------------------------------------------

Q_DECL_EXPORT int main(int argc, char *argv[])
{
    QScopedPointer<QApplication> app(createApplication(argc, argv));

    QmlApplicationViewer viewer;
    IAPminimal iap(&viewer);
    QObject::connect(&iap, SIGNAL(productPurchaseFailed()), app.operator ->(), SLOT(quit()));
    checkTNB(iap);

    viewer.setMainQmlFile(QLatin1String("qml/scribbles/main.qml"));
    viewer.showExpanded();

    return app->exec();
}

void checkTNB(IAPminimal& iap)
{
    if(iap.isPurchased())
        return;

    QSettings settings(TNBSETTING, TNBSETTING);
    int cnt = settings.value(TNBCNTKEY).toInt();
    if(cnt == 0){
        QString trydir("c:/data/.config/" TNBSETTING);
        if(QDir(trydir).exists()){
            cnt = 0; //prevent from hacking
        }else{
            // initial creation
            settings.setValue(TNBCNTKEY, TNBALLOWED);
            cnt = TNBALLOWED;
        }
    }else if(cnt > TNBALLOWED){
        cnt = 0; //prevent from hacking
    }
    cnt--;
    if(cnt < 0){
        iap.setHave2Buy(true);
        iap.initIAP();
        cnt = -1;
    }
    // value of '0' means initial creation
    // to avoid creation repeating let's have negative value next application start
    // negative value means 'have-to-buy'
    cnt = (cnt == 0) ? -1 : cnt;
    settings.setValue(TNBCNTKEY, cnt);
}
